﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace test6_f1
{
    public partial class Form1: Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadUserDirectories();

            // 设置 TreeView 的 BeforeExpand 事件
            treeView1.BeforeExpand += TreeView_BeforeExpand;
            treeView1.AfterSelect += treeView1_AfterSelect;
        }

        private void LoadUserDirectories()
        {
            treeView1.Nodes.Clear(); // 清空树形视图

            // 获取系统特殊文件夹路径
            string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string downloads = Path.Combine(userProfile, "Downloads");
            string pictures = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            string music = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
            string videos = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);

            // 创建根节点
            TreeNode rootNode = new TreeNode("用户目录", 0, 1);
            treeView1.Nodes.Add(rootNode);

            // 添加各用户目录节点
            AddDirectoryNode(rootNode, "桌面", desktop);
            AddDirectoryNode(rootNode, "文档", documents);
            AddDirectoryNode(rootNode, "下载", downloads);
            AddDirectoryNode(rootNode, "图片", pictures);
            AddDirectoryNode(rootNode, "音乐", music);
            AddDirectoryNode(rootNode, "视频", videos);

            rootNode.Expand(); // 展开根节点
        }

        private void AddDirectoryNode(TreeNode parentNode, string name, string path)
        {
            if (Directory.Exists(path))
            {
                TreeNode node = new TreeNode(name, 0, 1);
                node.Tag = path; // 将路径存储在Tag属性中
                parentNode.Nodes.Add(node);
                node.Nodes.Add(new TreeNode("加载中...")); // 添加虚拟节点
            }
        }

        private void TreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.Tag != null && Directory.Exists(e.Node.Tag.ToString()))
            {
                e.Node.Nodes.Clear(); // 清除虚拟节点
                LoadSubDirectories(e.Node); // 加载实际子目录
            }
        }

        private void LoadSubDirectories(TreeNode parentNode)
        {
            string path = parentNode.Tag.ToString();

            try
            {
                foreach (string dir in Directory.GetDirectories(path))
                {
                    DirectoryInfo di = new DirectoryInfo(dir);
                    TreeNode node = new TreeNode(di.Name, 0, 1);
                    node.Tag = dir;
                    parentNode.Nodes.Add(node);

                    // 如果目录有子目录，添加虚拟节点
                    if (Directory.GetDirectories(dir).Length > 0)
                    {
                        node.Nodes.Add(new TreeNode("加载中..."));
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                parentNode.Nodes.Add(new TreeNode("访问被拒绝"));
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag != null && Directory.Exists(e.Node.Tag.ToString()))
            {
                LoadDirectoryContents(e.Node.Tag.ToString()); // 加载目录内容
            }
        }

        private void LoadDirectoryContents(string path)
        {
            listView1.Items.Clear(); // 清空列表视图

            try
            {
                // 添加子目录
                foreach (string dir in Directory.GetDirectories(path))
                {
                    DirectoryInfo di = new DirectoryInfo(dir);
                    ListViewItem item = new ListViewItem(di.Name, 0);
                    item.SubItems.Add("文件夹");
                    item.SubItems.Add(di.LastWriteTime.ToString());
                    item.SubItems.Add("");
                    item.Tag = dir;
                    listView1.Items.Add(item);
                }

                // 添加文件
                foreach (string file in Directory.GetFiles(path))
                {
                    FileInfo fi = new FileInfo(file);
                    ListViewItem item = new ListViewItem(fi.Name, 1);
                    item.SubItems.Add(fi.Extension);
                    item.SubItems.Add(fi.LastWriteTime.ToString());
                    item.SubItems.Add(fi.Length.ToString("N0"));
                    item.Tag = file;
                    listView1.Items.Add(item);
                }
            }
            catch (UnauthorizedAccessException)
            {
                ListViewItem item = new ListViewItem("访问被拒绝", 1);
                listView1.Items.Add(item);
            }
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                string path = listView1.SelectedItems[0].Tag.ToString();

                if (Directory.Exists(path))
                {
                    // 如果是目录，在树视图中找到并展开对应节点
                    SelectTreeNodeByPath(path);
                }
                else if (File.Exists(path) && Path.GetExtension(path).Equals(".xml", StringComparison.OrdinalIgnoreCase))
                {
                    // 如果是XML文件，解析并显示内容
                    ShowXmlContent(path);
                }
                else
                {
                    // 其他文件尝试用默认程序打开
                    try
                    {
                        System.Diagnostics.Process.Start(path);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"无法打开文件: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void SelectTreeNodeByPath(string path)
        {
            TreeNode rootNode = treeView1.Nodes[0];
            SelectTreeNodeByPath(rootNode, path);
        }

        private bool SelectTreeNodeByPath(TreeNode parentNode, string path)
        {
            foreach (TreeNode node in parentNode.Nodes)
            {
                if (node.Tag != null && node.Tag.ToString().Equals(path, StringComparison.OrdinalIgnoreCase))
                {
                    treeView1.SelectedNode = node;
                    node.Expand();
                    return true;
                }

                if (SelectTreeNodeByPath(node, path))
                {
                    return true;
                }
            }

            return false;
        }

        private void ShowXmlContent(string xmlFilePath)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(xmlFilePath);

                // 创建XML查看器窗体
                Form xmlViewerForm = new Form();
                xmlViewerForm.Text = $"XML查看器 - {Path.GetFileName(xmlFilePath)}";
                xmlViewerForm.Width = 800;
                xmlViewerForm.Height = 600;

                // 添加TreeView控件
                TreeView xmlTreeView = new TreeView();
                xmlTreeView.Dock = DockStyle.Fill;
                xmlViewerForm.Controls.Add(xmlTreeView);

                // 构建XML树
                BuildXmlTree(xmlTreeView, doc.DocumentElement);

                xmlViewerForm.ShowDialog(); // 显示模态对话框
            }
            catch (Exception ex)
            {
                MessageBox.Show($"解析XML文件时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BuildXmlTree(TreeView treeView, XmlNode xmlNode)
        {
            treeView.Nodes.Clear();
            TreeNode rootTreeNode = new TreeNode(xmlNode.Name);
            treeView.Nodes.Add(rootTreeNode);
            AddXmlNodes(rootTreeNode, xmlNode); // 递归添加子节点
            rootTreeNode.Expand();
        }

        private void AddXmlNodes(TreeNode treeNode, XmlNode xmlNode)
        {
            // 添加属性
            if (xmlNode.Attributes != null)
            {
                foreach (XmlAttribute attr in xmlNode.Attributes)
                {
                    TreeNode attrNode = new TreeNode($"@{attr.Name} = {attr.Value}");
                    treeNode.Nodes.Add(attrNode);
                }
            }

            // 添加子节点
            foreach (XmlNode childNode in xmlNode.ChildNodes)
            {
                if (childNode.NodeType == XmlNodeType.Element)
                {
                    TreeNode childTreeNode = new TreeNode(childNode.Name);
                    treeNode.Nodes.Add(childTreeNode);
                    AddXmlNodes(childTreeNode, childNode); // 递归
                }
                else if (childNode.NodeType == XmlNodeType.Text)
                {
                    TreeNode textNode = new TreeNode($"文本: {childNode.Value}");
                    treeNode.Nodes.Add(textNode);
                }
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit(); // 退出应用程序
        }
    }
}


